package com.baomidou.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiResult;
import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.baomidou.springboot.ErrorCode;
import com.baomidou.springboot.entity.TbUser;
import com.baomidou.springboot.mapper.TbUserMapper;
import com.baomidou.springboot.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("/users")
@CrossOrigin()
public class TbUserController {

    @Resource
    private TbUserService tbUserService;

    @Autowired
    private TbUserMapper tbUserMapper;

    @GetMapping
    public List<TbUser> list() {
        return tbUserService.list();
    }

    @GetMapping("/{id}")
    public ApiResult getById(@PathVariable Integer id) {
        TbUser byId = tbUserService.getById(id);

        if (!Objects.isNull(byId)) {
            return ApiResult.ok(byId);
        }
        return ApiResult.failed("没有此用户的信息");
    }

    //注册接口
    @PostMapping("/reg")
    public ApiResult save(@RequestBody TbUser user) {
        user.setMoney(String.valueOf(0));
        user.setToken(UUID.randomUUID().toString());
        if (tbUserService.save(user)) {
            return ApiResult.restResult(user, ErrorCode.SUCCESS);
        }
        return ApiResult.failed("用户注册失败");
    }

    // 登录接口
    @GetMapping("/login")
    public ApiResult login (String u , String p) {
        List<TbUser> tbUser = tbUserMapper.selectList(new QueryWrapper<TbUser>().lambda()
                .eq(TbUser::getUsername, u)
                .eq(TbUser::getPassword, p));
        if(tbUser.size()==0) {
            return ApiResult.failed("登录失败");
        }
        ApiResult ok = ApiResult.ok(tbUser);
        ok.setCode(ErrorCode.SUCCESS.getCode());
        return ok;
    }

    @PutMapping("/{id}")
    public ApiResult<TbUser> updateById(@PathVariable Integer id, @RequestBody TbUser user) {
        user.setId(id);
        if(tbUserService.updateById(user)) {
            return ApiResult.failed("用户id错误");
        }
        return ApiResult.ok(user);
    }

    @DeleteMapping("/{id}")
    public boolean removeById(@PathVariable Integer id) {
        return tbUserService.removeById(id);
    }
}
